package com.martin.fastframe.ui.danmu

import android.animation.ValueAnimator
import android.view.View
import android.view.ViewGroup
import android.view.animation.LinearInterpolator
import android.widget.TextView
import com.martin.fastframe.R
import com.martin.lib_base.ktx.loge
import dev.utils.app.ScreenUtils

class DanMuBean(
    private val name: String,
    private val message: String
) {

    /**
     * 弹幕宽度
     * 程序处理,开发者不需要处理
     */
    private var width: Int = 0

    /**
     * 弹幕View
     */
    var view: View? = null

    //弹道定位
    var index: Int = 0

    /**
     * 显示完全状态
     */
    var displayState = false

    /**
     * 设置弹幕View
     */
    fun setDanMuView(
        view: View, index: Int,
        /**
         * 显示完全回调
         * 通知可以显示下一条弹幕
         */
        displayCallBack: () -> Unit
    ) {
        this.view = view
        this.index = index

        //设置弹幕文本信息
        view.findViewById<TextView>(R.id.tv_name).text = name
        view.findViewById<TextView>(R.id.tv_message).text = message
        //重新计算弹幕宽度
        view.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED)
        width = view.measuredWidth

        //设置位移动画
        val screenWidth = ScreenUtils.getScreenWidth()
        val animator = ValueAnimator.ofInt(screenWidth, -width)
        animator.addUpdateListener {
            val toX = it.animatedValue as Int
            view.x = toX.toFloat()
            //处理显示完全事件
            if (screenWidth - toX - width - 10 > 0 && !displayState) {
                displayCallBack()
                displayState = true
            }

            //处理完全移出视图
            if (toX <= -width && view.parent != null) {
                release()
            }
        }
        animator.interpolator = LinearInterpolator()
        animator.duration = 6000
        animator.start()
    }

    /**
     * 释放
     */
    private fun release() {
        view?.parent?.let {
            val group = it as ViewGroup
            group.removeView(view)
            view = null
        }
    }

}